/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.util.java;

import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public final class HtmlUtils {
	private HtmlUtils() {}  // never

	public static String htmlEncode(String s) {
		char[] a = s.toCharArray();
		StringBuilder buf = new StringBuilder();
		for( int i=0; i<a.length; i++ ) {
			char c = a[i];
			switch(c) {
			case '&':
				buf.append("&amp;");
				break;
			case '<':
				buf.append("&lt;");
				break;
			case '>':
				buf.append("&gt;");
				break;
			case '"':
				buf.append("&quot;");
				break;
			default:
				buf.append(c);
			}
		}
		return buf.toString();
	}

	private static final Pattern entityPtn = Pattern.compile(
		"&#(\\d+);"
	);

	public static String htmlDecode(String s) {
		StringBuffer buf = new StringBuffer();
		Matcher m = entityPtn.matcher(s);
		while( m.find() ) {
			String entity = new String(new char[]{(char)Integer.parseInt(m.group(1))});
			m.appendReplacement(buf,entity);
		}
		m.appendTail(buf);
		s = buf.toString();
		s = s.replace("&nbsp;"," ");
		s = s.replace("&quot;","\"");
		s = s.replace("&gt;",">");
		s = s.replace("&lt;","<");
		s = s.replace("&amp;","&");
		return s;
	}

	public static String javascriptStringEncode(String s) {
		char[] a = s.toCharArray();
		StringBuilder buf = new StringBuilder();
		for( int i=0; i<a.length; i++ ) {
			char c = a[i];
			switch(c) {
			case '\\':
				buf.append("\\\\");
				break;
			case '\'':
				buf.append("\\'");
				break;
			case '\"':
				buf.append("\\\"");
				break;
			case '\n':
				buf.append("\\n");
				break;
			case '\r':
				buf.append("\\r");
				break;
			case '<':
				buf.append("\\x3C");
				break;
			case '>':
				buf.append("\\x3E");
				break;
			case '=':
				buf.append("\\x3D");
				break;
			default:
				buf.append(c);
			}
		}
		return buf.toString();
	}

	public static String breakUp(final String text,int maxSize,boolean hasCharEntities) {
		StringBuilder buf = new StringBuilder();
		int n = 0;
		int len = text.length();
		for( int i=0; i<len; i++ ) {
			char c = text.charAt(i);
			if( hasCharEntities && c=='&' ) {
				do {
					buf.append(c);
					c = text.charAt(++i);
				} while( c != ';' );
			} else if( Character.isWhitespace(c) ) {
				n = 0;
			} else {
				if( ++n > maxSize ) {
					buf.append("<wbr />");
					n = 0;
				}
			}
			buf.append(c);
		}
		return buf.toString();
	}

	public static String urlEncode(String s) {
		try {
			return URLEncoder.encode(s,"UTF-8");
		} catch(java.io.UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String urlDecode(String s) {
		try {
			return URLDecoder.decode(s,"UTF-8");
		} catch(java.io.UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String toJson(Object object) {
		StringBuilder builder = new StringBuilder("{");
		try {
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Object value = field.get(object);
				if (value != null) {
					if (builder.length() > 1)
						builder.append(',');
					builder.append('\"').append(field.getName()).append("\": \"").append(javascriptStringEncode(value.toString())).append("\"\n");
				}
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		builder.append('}');
		return builder.toString();
	}

}
